package greedyAlgorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class threeSum {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        //先排序
        Arrays.sort(nums);
        int n=nums.length;
        for (int i = 0; i <n ; ) {
            int left=i+1;
            int right=n-1;
            int target=-nums[i];
            if(nums[i]>0){
                break;
            }
            while (left<right){
                int sum=nums[left]+nums[right];
                if(sum>target){
                    right--;
                }else if(sum<target){
                    left++;
                }else {
                    list.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    left++;
                    right--;
                    while (left<right&&nums[left]==nums[left-1]){
                        left++;
                    }
                    while (left<right&&nums[right]==nums[right+1]){
                        right--;
                    }
                }
            }
            i++;
            while (i<n&&nums[i]==nums[i-1]){
                i++;
            }
        }
        return list;
    }

    public static void main(String[] args) {
        int[] arrays = {-1,0,1,2,-1,-4};
        System.out.println(threeSum(arrays));
    }
}
